import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:ty_smart_watch/ble/ble_util.dart';
import 'package:ty_smart_watch/ble/protocol_data_util.dart';
import 'package:ty_smart_watch/common/function_id.dart';
import 'package:ty_smart_watch/common/images_url.dart';
import 'package:ty_smart_watch/page/watch_setting_page/controller/watch_setting_controller.dart';
import 'package:ty_smart_watch/utils/Log.dart';

class WatchSosSettingPage extends StatefulWidget {
  const WatchSosSettingPage({super.key});

  @override
  State<WatchSosSettingPage> createState() => _WatchSosSettingPageState();
}

class _WatchSosSettingPageState extends State<WatchSosSettingPage> {
  int _functionId = 0; //功能id
  String _mac = ""; //设备地址
  final _controller = Get.put(WatchSettingController());
  final int _SOS_TYPE_NEW = 0;
  final int _SOS_TYPE_MODIFY = 1;
  final int _SOS_TYPE_DELETE = 2;

  @override
  void initState() {
    super.initState();
    _functionId = Get.arguments["id"];
    _mac = Get.arguments["mac"];
    Log.d("页面收到的数据：$_functionId > $_mac");
    _controller.getBleData(_mac, _functionId);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("SOS联系人"),
        centerTitle: true,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios),
          onPressed: () {
            Get.back();
          },
        ),
        actions: [
          IconButton(
              onPressed: () {
                _createSosDialog();
              },
              icon: const Icon(
                Icons.add_circle_outline_outlined,
                // color: Colors.red,
              ))
        ],
      ),
      body: Obx(
        () => ListView.builder(
          itemCount: _controller.sosList.value.length,
          itemBuilder: (BuildContext context, int index) {
            final item = _controller.sosList.value[index];
            return Container(
              margin: const EdgeInsets.fromLTRB(10, 10, 10, 0),
              padding: const EdgeInsets.symmetric(horizontal: 10),
              decoration: const BoxDecoration(
                  border: Border(bottom: BorderSide(width: 1, color: Color(0xffe5e5e5)))),
              child: ListTile(
                splashColor: Colors.transparent,
                onTap: () {
                  _modifySosDialog(item);
                },
                onLongPress: () {
                  _deleteSosDialog(item);
                },
                leading: Image.asset(
                  ICON_WATHC_STYLE_1,
                  width: 32,
                  height: 32,
                ),
                title: Text(item.name),
                subtitle: Text(item.phone),
                contentPadding: const EdgeInsets.symmetric(vertical: 2),
              ),
            );
          },
        ),
      ),
    );
  }

  _createSos(String name, String phone) {
    Log.d("新增联系人");
    _doSosTask(_SOS_TYPE_NEW, 0, phone, name);
  }

  _modifySos(int id, String name, String phone) {
    Log.d("新增联系人");
    _doSosTask(_SOS_TYPE_MODIFY, id, phone, name);
  }

  // _modifySos(SosBean item) {
  //   Log.d("修改联系人");
  //   _doSosTask(_SOS_TYPE_MODIFY, item.id, item.phone, item.name);
  // }

  ///删除紧急联系人
  _deleteSos(SosBean item) {
    Log.d("删除 ${item.id}");
    _doSosTask(_SOS_TYPE_DELETE, item.id, item.phone, item.name);
  }

  ///删除紧急联系人弹窗
  _deleteSosDialog(SosBean item) {
    Get.defaultDialog(
      title: "删除紧急联系人",
      middleText: "确定删除 ${item.name}",
      //确定按钮
      confirm: ElevatedButton(
          onPressed: () {
            //单击后删除弹框
            _deleteSos(item);
            Get.back();
          },
          child: const Text("删除")),
      //取消按钮
      cancel: ElevatedButton(
          onPressed: () {
            //单击后删除弹框
            Get.back();
          },
          child: const Text("取消")),
    );
  }

  _createSosDialog() {
    TextEditingController nameController = TextEditingController();
    TextEditingController phoneController = TextEditingController();
    Get.defaultDialog(
      title: '新增紧急联系人',
      content: Column(
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              const Text("姓名"),
              const SizedBox(width: 20),
              Expanded(
                child: TextField(
                  controller: nameController,
                  onChanged: (v) {},
                  decoration: const InputDecoration(
                    // hintText: "请输入持续天数(天)",
                    hintStyle: TextStyle(
                      color: Color(0xFF969696),
                    ), /*border: InputBorder.none*/
                  ),
                  // keyboardType: TextInputType.number,
                  // inputFormatters: [
                  // FilteringTextInputFormatter.digitsOnly, //数字，只能是整数
                  // ],
                  maxLines: 1,
                ),
              ),
              const SizedBox(width: 20),
            ],
          ),
          Row(
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              const Text("电话"),
              const SizedBox(width: 20),
              Expanded(
                child: TextField(
                  controller: phoneController,
                  onChanged: (v) {},
                  decoration: const InputDecoration(
                    // hintText: "请输入持续天数(天)",
                    hintStyle: TextStyle(
                      color: Color(0xFF969696),
                    ), /*border: InputBorder.none*/
                  ),
                  keyboardType: TextInputType.number,
                  inputFormatters: [
                    FilteringTextInputFormatter.digitsOnly, //数字，只能是整数
                  ],
                  maxLines: 1,
                ),
              ),
              const SizedBox(width: 20),
            ],
          ),
        ],
      ),
      textConfirm: '确定',
      textCancel: '取消',
      onConfirm: () {
        // 用户点击确认按钮时执行的操作
        _createSos(nameController.text, phoneController.text);
        Get.back();
      },
      onCancel: () {
        // 用户点击取消按钮时执行的操作
      },
    );
  }

  _modifySosDialog(SosBean sos) {
    TextEditingController nameController = TextEditingController();
    nameController.value = TextEditingValue(
      text: sos.name,
      selection: TextSelection.fromPosition(
        TextPosition(affinity: TextAffinity.downstream, offset: sos.name.length),
      ),
    );
    TextEditingController phoneController = TextEditingController();
    phoneController.value = TextEditingValue(
      text: sos.phone,
      selection: TextSelection.fromPosition(
        TextPosition(affinity: TextAffinity.downstream, offset: sos.name.length),
      ),
    );

    Get.defaultDialog(
      title: '修改紧急联系人',
      content: Column(
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              const Text("姓名"),
              const SizedBox(width: 20),
              Expanded(
                child: TextField(
                  controller: nameController,
                  onChanged: (v) {},
                  decoration: const InputDecoration(
                    // hintText: "请输入持续天数(天)",
                    hintStyle: TextStyle(
                      color: Color(0xFF969696),
                    ), /*border: InputBorder.none*/
                  ),
                  // keyboardType: TextInputType.number,
                  // inputFormatters: [
                  // FilteringTextInputFormatter.digitsOnly, //数字，只能是整数
                  // ],
                  maxLines: 1,
                ),
              ),
              const SizedBox(width: 20),
            ],
          ),
          Row(
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              const Text("电话"),
              const SizedBox(width: 20),
              Expanded(
                child: TextField(
                  controller: phoneController,
                  onChanged: (v) {},
                  decoration: const InputDecoration(
                    // hintText: "请输入持续天数(天)",
                    hintStyle: TextStyle(
                      color: Color(0xFF969696),
                    ), /*border: InputBorder.none*/
                  ),
                  keyboardType: TextInputType.number,
                  inputFormatters: [
                    FilteringTextInputFormatter.digitsOnly, //数字，只能是整数
                  ],
                  maxLines: 1,
                ),
              ),
              const SizedBox(width: 20),
            ],
          ),
        ],
      ),
      textConfirm: '确定',
      textCancel: '取消',
      onConfirm: () {
        // 用户点击确认按钮时执行的操作
        _modifySos(sos.id, nameController.text, phoneController.text);
        Get.back();
      },
      onCancel: () {
        // 用户点击取消按钮时执行的操作
      },
    );
  }

  _doSosTask(int type, int id, String number, String name) {
    var data = ProtocolDataUtil.sos(type, id, number, name);
    var sos = BleUtil.makeWriteData(functionId: SOS, data: data);
    Log.d("发送删除sos数据： $sos");
    BleUtil.writeBleData(_mac, sos);
  }
}
